package drds.server.net.packet;

import java.nio.ByteBuffer;

import drds.server.buffer.ByteBufferList;
import drds.server.net.SessionContext$LifeCycle;

/**
 * From server to client after command, if no error and result set -- that is,
 * if the command was a query which returned a result set. The Result Set Header
 * Packet is the first of several, possibly many, packets that the server sends
 * for result sets. The order of packets for a result set is:
 * 
 * <pre>
 * (Result Set Header Packet)   the number of columns
 * (Field Packets)              column descriptors
 * (EOF Packet)                 marker: end of Field Packets
 * (Row Data Packets)           row contents
 * (EOF Packet)                 marker: end of Data Packets
 * 
 * Bytes                        Name
 * -----                        ----
 * 1-9   (Length-Coded-Binary)  field_count
 * 1-9   (Length-Coded-Binary)  extra
 * 
 * @see http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#Result_Set_Header_Packet
 * </pre>
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class ResultSetHeaderPacket extends Packet {

	public int fieldCount;

	public void read(byte[] bytes) {
		BytesHolder bytesHolder = new BytesHolder(bytes);
		this.packetLength = bytesHolder.readInt3();
		this.packetId = bytesHolder.read();
		this.fieldCount = (int) bytesHolder.readLength();
	}

	@Override
	public ByteBuffer write(ByteBuffer byteBuffer, SessionContext$LifeCycle sessionContext, boolean writeSocketIfFull) {
		int size = computePacketSize();
		byteBuffer = sessionContext.checkWriteByteBuffer(byteBuffer, sessionContext.getPacketHeaderSize() + size, writeSocketIfFull);
		ByteBufferUtil.writeInt3(byteBuffer, size);
		byteBuffer.put(packetId);
		ByteBufferUtil.writeLength(byteBuffer, fieldCount);
		return byteBuffer;
	}

	public void write(ByteBufferList byteBufferList) {
		int size = computePacketSize();
		ByteBuffer byteBuffer = byteBufferList.checkWritingByteBufferCapacity(packetHeaderSize + size);
		ByteBufferUtil.writeInt3(byteBuffer, size);
		byteBuffer.put(packetId);
		ByteBufferUtil.writeLength(byteBuffer, fieldCount);
	}

	@Override
	public int computePacketSize() {
		int size = ByteBufferUtil.getLength(fieldCount);
		return size;
	}

}